<template>
  <div class="main">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">车辆管理</h1>
    </div>

    <!-- 操作按钮栏 -->
    <div class="action-bar">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <IconifyIconOffline icon="ep:plus" />
          添加
        </el-button>
        <el-button type="success" @click="showImportDialog">
          <IconifyIconOffline icon="ep:upload" />
          导入
        </el-button>
        <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click="handleBatchDelete"
        >
          <IconifyIconOffline icon="ep:delete" />
          删除
        </el-button>
      </div>
      
      <div class="search-filters">
        <el-select
          v-model="searchForm.cellId"
          placeholder="所属小区"
          style="width: 140px;"
          clearable
        >
          <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
          />
        </el-select>
        <el-input
          v-model="searchForm.plateNo"
          placeholder="车牌号"
          style="width: 140px;"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-input
          v-model="searchForm.ownerName"
          placeholder="车主姓名"
          style="width: 140px;"
          clearable
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">
          <IconifyIconOffline icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="handleReset">
          <IconifyIconOffline icon="ep:refresh" />
          重置
        </el-button>
      </div>
    </div>

    <!-- 车辆列表表格 -->
    <div v-loading="loading" class="table-container">
      <el-table
        ref="tableRef"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="cellName" label="小区名称" width="150" />
        <el-table-column prop="plateNo" label="登记车牌" width="150" />
        <el-table-column prop="ownerName" label="车主" width="120" />
        <el-table-column prop="contactPhone" label="联系方式" width="150" />
        <el-table-column prop="vehicleSpaces" label="关联车位" width="200">
          <template #default="{ row }">
            <div class="space-tags-container">
              <el-tag 
                v-for="vehicleSpace in row.vehicleSpaces" 
                :key="vehicleSpace.id"
                size="small"
                :class="getSpaceTagClass(vehicleSpace.bindType)"
                @click="showVehicleSpaceDetail(vehicleSpace, row)"
              >
                {{ getSpaceNumber(vehicleSpace.parkingSpaceId) }}{{ getBindTypeText(vehicleSpace.bindType) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleSpaces" label="授权开始时间" width="150">
          <template #default="{ row }">
            <div class="time-container">
              <div 
                v-for="vehicleSpace in row.vehicleSpaces" 
                :key="vehicleSpace.id" 
                class="time-item"
              >
                {{ formatDate(vehicleSpace.authorizeStart) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleSpaces" label="授权结束时间" width="150">
          <template #default="{ row }">
            <div class="time-container">
              <div 
                v-for="vehicleSpace in row.vehicleSpaces" 
                :key="vehicleSpace.id" 
                class="time-item"
              >
                {{ formatDate(vehicleSpace.authorizeEnd) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="success" @click="handleBindParkingSpace(row)">
              绑定车位
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>


    <!-- 车辆表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="小区名称" prop="cellId">
          <el-select
            v-model="formData.cellId"
            placeholder="请选择小区"
            style="width: 100%"
          >
            <el-option
              v-for="community in communityList"
              :key="community.id"
              :label="community.name"
              :value="community.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登记车牌" prop="plateNo">
          <el-input v-model="formData.plateNo" placeholder="请输入登记车牌" />
        </el-form-item>
        <el-form-item label="车主" prop="ownerName">
          <el-input v-model="formData.ownerName" placeholder="请输入车主姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactPhone">
          <el-input v-model="formData.contactPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="车主类型" prop="ownerType">
          <el-select v-model="formData.ownerType" placeholder="请选择车主类型" style="width: 100%">
            <el-option label="业主" :value="1" />
            <el-option label="租户" :value="2" />
            <el-option label="访客" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 绑定车位对话框 -->
    <el-dialog
      v-model="bindParkingSpaceDialogVisible"
      title="绑定车位"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="bindParkingSpaceFormRef"
        :model="bindParkingSpaceForm"
        :rules="bindParkingSpaceFormRules"
        label-width="120px"
      >
        <el-form-item label="车辆信息" prop="vehicleId">
          <el-input v-model="bindParkingSpaceForm.vehicleId" disabled />
        </el-form-item>
        
        <el-form-item label="选择车位" prop="parkingSpaceId">
          <el-select 
            v-model="bindParkingSpaceForm.parkingSpaceId" 
            placeholder="请输入车位编号搜索" 
            style="width: 100%"
            filterable
            remote
            :remote-method="searchParkingSpaces"
            :loading="parkingSpaceSearchLoading"
            @change="handleParkingSpaceChange"
          >
            <el-option
              v-for="space in parkingSpaceList"
              :key="space.id"
              :label="`${space.spaceNo} - ${space.location || '暂无位置信息'}`"
              :value="space.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="绑定类型" prop="bindType">
          <el-radio-group v-model="bindParkingSpaceForm.bindType">
            <el-radio :value="1">长期绑定</el-radio>
            <el-radio :value="2">临时绑定</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="授权开始时间" prop="authorizeStart">
          <el-date-picker
            v-model="bindParkingSpaceForm.authorizeStart"
            type="datetime"
            placeholder="请选择授权开始时间"
            style="width: 100%"
            :disabled-date="disabledStartDate"
            :disabled-time="disabledStartTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="授权结束时间" prop="authorizeEnd">
          <el-date-picker
            v-model="bindParkingSpaceForm.authorizeEnd"
            type="datetime"
            placeholder="请选择授权结束时间"
            style="width: 100%"
            :disabled-date="disabledEndDate"
            :disabled-time="disabledEndTime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindParkingSpaceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBindParkingSpaceSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入车辆对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入车辆"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="import-dialog-content">
        <el-upload
          ref="uploadRef"
          class="upload-area"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><Upload /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传.xlsx/.xls文件，且文件大小不超过10MB
            </div>
          </template>
        </el-upload>

        <div class="import-tips">
          <h4>导入说明：</h4>
          <p>1. 请按照模板格式填写数据</p>
          <p>2. 车主类型请填写"业主/租户/访客/其他"</p>
          <p>3. 确保必填字段都已填写完整</p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button @click="handleDownloadTemplate">下载模板</el-button>
          <el-button
            type="primary"
            :loading="importLoading"
            @click="handleImport"
          >
            确认导入
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 车辆车位详情对话框 -->
    <el-dialog
      v-model="vehicleSpaceDetailVisible"
      title="车位绑定详情"
      width="500px"
      :close-on-click-modal="false"
    >
      <div v-if="currentVehicleSpace" class="vehicle-space-detail">
        <div class="detail-row">
          <span class="label">车牌号：</span>
          <span class="value">{{ currentVehicleSpace.plateNo }}</span>
        </div>
        <div class="detail-row">
          <span class="label">车位编号：</span>
          <span class="value">{{ getSpaceNumber(currentVehicleSpace.parkingSpaceId) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">绑定类型：</span>
          <span class="value">{{ currentVehicleSpace.bindType === 1 ? '长期绑定' : '临时绑定' }}</span>
        </div>
        <div class="detail-row">
          <span class="label">授权开始时间：</span>
          <span class="value">{{ formatDateTime(currentVehicleSpace.authorizeStart) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">授权结束时间：</span>
          <span class="value">{{ formatDateTime(currentVehicleSpace.authorizeEnd) }}</span>
        </div>
        <div class="detail-row">
          <span class="label">状态：</span>
          <el-tag :type="currentVehicleSpace.status === 1 ? 'success' : 'danger'">
            {{ currentVehicleSpace.status === 1 ? '有效' : '无效' }}
          </el-tag>
        </div>
        <div class="detail-row">
          <span class="label">创建人：</span>
          <span class="value">{{ currentVehicleSpace.createdBy || '系统' }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="vehicleSpaceDetailVisible = false">关闭</el-button>
        <el-button 
          type="danger" 
          @click="handleUnbindVehicleSpace"
          :loading="unbindLoading"
        >
          解绑
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import {
  getVehicleList,
  createVehicle,
  updateVehicle,
  deleteVehicle,
  batchDeleteVehicle,
  getVehicleById,
  importVehicles,
  exportVehicleTemplate,
  type Vehicle,
  type VehicleQueryParams,
  type CreateVehicleRequest,
} from "@/api/vehicle";
import { findAllCells } from "@/api/cell";
import {
  bindVehicleToParkingSpace,
  searchParkingSpaces as searchParkingSpacesApi,
  getParkingSpaceById,
  unbindVehicleFromParkingSpace,
  type BindVehicleRequest,
  type ParkingSpace,
} from "@/api/parkingSpace";

// 车辆状态标签映射
const VEHICLE_STATUS_LABELS = {
  1: "有效",
  2: "过期",
  3: "待审核",
} as const;

defineOptions({ name: "DataCenterVehicle" });

// 响应式数据
const loading = ref(false);
const tableData = ref<Vehicle[]>([]);
const selectedRows = ref<Vehicle[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref("");
const communityList = ref<any[]>([]);

// 车辆车位详情相关
const vehicleSpaceDetailVisible = ref(false);
const currentVehicleSpace = ref<any>(null);
const unbindLoading = ref(false);

// 搜索表单
const searchForm = reactive<VehicleQueryParams>({
  cellId: undefined,
  plateNo: undefined,
  ownerName: undefined,
});

// 绑定车位相关
const bindParkingSpaceDialogVisible = ref(false);
const bindParkingSpaceFormRef = ref<FormInstance>();
const bindParkingSpaceForm = reactive<Partial<BindVehicleRequest>>({
  vehicleId: undefined,
  parkingSpaceId: undefined,
  bindType: 1,
  authorizeStart: undefined,
  authorizeEnd: undefined,
});
const parkingSpaceList = ref<ParkingSpace[]>([]);
const parkingSpaceSearchLoading = ref(false);
const currentVehicle = ref<Vehicle | null>(null);

// 车位编号缓存
const parkingSpaceNumbers = ref<Map<number, string>>(new Map());
// 正在加载的车位ID集合，避免重复请求
const loadingParkingSpaceIds = ref<Set<number>>(new Set());

// 导入相关
const importDialogVisible = ref(false);
const importLoading = ref(false);
const selectedFile = ref<File | null>(null);
const uploadRef = ref();

// 分页数据
const pagination = reactive({
  page: 1,
  limit: 10,
  total: 0,
});

// 表单数据
const formData = reactive<Partial<CreateVehicleRequest> & { id?: number }>({
  id: undefined,
  cellId: undefined,
  plateNo: "",
  ownerName: "",
  contactPhone: "",
  ownerType: 1,
  remark: "",
});

// 表单验证规则
const formRules: FormRules = {
  cellId: [{ required: true, message: "请选择小区", trigger: "change" }],
  plateNo: [{ required: true, message: "请输入登记车牌", trigger: "blur" }],
  ownerName: [{ required: true, message: "请输入车主姓名", trigger: "blur" }],
  contactPhone: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
  ownerType: [{ required: true, message: "请选择车主类型", trigger: "change" }],
};

// 绑定车位表单验证规则
const bindParkingSpaceFormRules: FormRules = {
  vehicleId: [{ required: true, message: "车辆ID不能为空", trigger: "blur" }],
  parkingSpaceId: [{ required: true, message: "请选择车位", trigger: "change" }],
  bindType: [{ required: true, message: "请选择绑定类型", trigger: "change" }],
  authorizeStart: [{ required: true, message: "请选择授权开始时间", trigger: "change" }],
  authorizeEnd: [{ required: true, message: "请选择授权结束时间", trigger: "change" }],
};

// 表单引用
const formRef = ref<FormInstance>();

// 计算属性
const currentQueryParams = computed(() => ({
  page: pagination.page - 1, // 后端从0开始
  limit: pagination.limit,
  ...searchForm,
}));

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 获取绑定类型文本
const getBindTypeText = (bindType: number): string => {
  return bindType === 1 ? "长" : "临";
};

// 获取车位标签样式类
const getSpaceTagClass = (bindType: number): string => {
  return bindType === 1 ? "space-tag-long" : "space-tag-temp";
};

// 显示车辆车位详情
const showVehicleSpaceDetail = (vehicleSpace: any, vehicle: Vehicle) => {
  currentVehicleSpace.value = {
    ...vehicleSpace,
    plateNo: vehicle.plateNo
  };
  vehicleSpaceDetailVisible.value = true;
};

// 解绑车辆车位
const handleUnbindVehicleSpace = async () => {
  if (!currentVehicleSpace.value) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要解除车辆 ${currentVehicleSpace.value.plateNo} 与车位 ${getSpaceNumber(currentVehicleSpace.value.parkingSpaceId)} 的绑定吗？`,
      '确认解绑',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    unbindLoading.value = true;
    const response = await unbindVehicleFromParkingSpace({
      parkingSpaceId: currentVehicleSpace.value.parkingSpaceId,
      vehicleId: currentVehicleSpace.value.vehicleId
    });
    
    if (response.code === 0) {
      ElMessage.success("解绑成功");
      vehicleSpaceDetailVisible.value = false;
      // 刷新车辆列表
      await fetchVehicleList();
    } else {
      ElMessage.error(response.message || "解绑失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("解绑失败:", error);
      ElMessage.error("解绑失败");
    }
  } finally {
    unbindLoading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  const date = new Date(dateString);
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
};

// 获取车位编号（同步版本，用于模板显示）
const getSpaceNumber = (parkingSpaceId: number): string => {
  // 检查缓存
  if (parkingSpaceNumbers.value.has(parkingSpaceId)) {
    return parkingSpaceNumbers.value.get(parkingSpaceId)!;
  }
  
  // 异步加载车位编号
  loadParkingSpaceNumber(parkingSpaceId);
  
  return parkingSpaceId.toString(); // 暂时返回ID
};

// 异步加载车位编号
const loadParkingSpaceNumber = async (parkingSpaceId: number) => {
  // 如果已有缓存或正在加载，直接返回
  if (parkingSpaceNumbers.value.has(parkingSpaceId) || loadingParkingSpaceIds.value.has(parkingSpaceId)) {
    return;
  }
  
  // 标记为正在加载
  loadingParkingSpaceIds.value.add(parkingSpaceId);
  
  try {
    const response = await getParkingSpaceById(parkingSpaceId);
    if (response.code === 0 && response.data) {
      const spaceNo = response.data.spaceNo;
      // 缓存结果
      parkingSpaceNumbers.value.set(parkingSpaceId, spaceNo);
    }
  } catch (error) {
    console.error("获取车位编号失败:", error);
  } finally {
    // 移除加载标记
    loadingParkingSpaceIds.value.delete(parkingSpaceId);
  }
};

// 批量预加载车位编号
const preloadParkingSpaceNumbers = (vehicles: Vehicle[]) => {
  // 收集所有需要加载的车位ID
  const parkingSpaceIds = new Set<number>();
  
  vehicles.forEach(vehicle => {
    if (vehicle.vehicleSpaces && Array.isArray(vehicle.vehicleSpaces)) {
      vehicle.vehicleSpaces.forEach(vehicleSpace => {
        const parkingSpaceId = vehicleSpace.parkingSpaceId;
        // 只加载未缓存且未在加载中的车位ID
        if (!parkingSpaceNumbers.value.has(parkingSpaceId) && 
            !loadingParkingSpaceIds.value.has(parkingSpaceId)) {
          parkingSpaceIds.add(parkingSpaceId);
        }
      });
    }
  });
  
  // 批量加载车位编号
  parkingSpaceIds.forEach(parkingSpaceId => {
    loadParkingSpaceNumber(parkingSpaceId);
  });
};

// 获取车辆列表
const fetchVehicleList = async () => {
  try {
    loading.value = true;
    const response = await getVehicleList(currentQueryParams.value);
    console.log("车辆列表响应:", response); // 添加调试日志
    if (response.code === 0 && response.data) {
      // 处理后端返回的数据结构
      if (response.data.list && Array.isArray(response.data.list)) {
        tableData.value = response.data.list;
        pagination.total = response.data.total || response.data.list.length;
        // 批量预加载车位编号
        preloadParkingSpaceNumbers(response.data.list);
      } else if (Array.isArray(response.data)) {
        tableData.value = response.data;
        pagination.total = response.data.length;
        // 批量预加载车位编号
        preloadParkingSpaceNumbers(response.data);
      } else {
        tableData.value = [];
        pagination.total = 0;
      }
    } else {
      ElMessage.error(response.message || "获取车辆列表失败");
    }
  } catch (error) {
    console.error("获取车辆列表失败:", error);
    ElMessage.error("获取车辆列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取小区列表
const fetchCommunityList = async () => {
  try {
    const response = await findAllCells();
    if (response.code === 0 && response.data) {
      communityList.value = response.data;
    }
  } catch (error) {
    console.error("获取小区列表失败:", error);
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.page = 1;
  fetchVehicleList();
};

// 重置搜索
const handleReset = () => {
  searchForm.cellId = undefined;
  searchForm.plateNo = undefined;
  searchForm.ownerName = undefined;
  pagination.page = 1;
  fetchVehicleList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.limit = size;
  pagination.page = 1;
  fetchVehicleList();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchVehicleList();
};

// 表格选择改变
const handleSelectionChange = (selection: Vehicle[]) => {
  selectedRows.value = selection;
};

// 添加车辆
const handleAdd = () => {
  dialogTitle.value = "添加车辆";
  Object.assign(formData, {
    cellId: undefined,
    plateNo: "",
    ownerName: "",
    contactPhone: "",
    ownerType: 1,
    remark: "",
  });
  dialogVisible.value = true;
};

// 编辑车辆
const handleEdit = async (row: Vehicle) => {
  try {
    dialogTitle.value = "编辑车辆";
    // 获取完整的车辆信息用于回显
    const response = await getVehicleById(row.id);
    if (response.code === 0 && response.data) {
      Object.assign(formData, {
        id: response.data.id,
        cellId: response.data.cellId,
        plateNo: response.data.plateNo,
        ownerName: response.data.ownerName,
        contactPhone: response.data.contactPhone,
        ownerType: response.data.ownerType || 1,
        remark: response.data.remark || "",
      });
      dialogVisible.value = true;
    } else {
      ElMessage.error(response.message || "获取车辆信息失败");
    }
  } catch (error) {
    console.error("获取车辆信息失败:", error);
    ElMessage.error("获取车辆信息失败");
  }
};

// 删除车辆
const handleDelete = async (row: Vehicle) => {
  try {
    // 检查是否绑定了车位
    const hasBindings = row.vehicleSpaces && row.vehicleSpaces.length > 0;
    
    let confirmMessage = `确定要删除车辆"${row.plateNo}"吗？`;
    if (hasBindings) {
      confirmMessage = `车辆"${row.plateNo}"已绑定车位，删除后将同时解除所有车位绑定。确定要继续删除吗？`;
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );
    
    const response = await deleteVehicle(row.id);
    if (response.code === 0) {
      ElMessage.success("删除成功");
      fetchVehicleList();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除车辆失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的车辆");
    return;
  }

  try {
    // 检查是否有车辆绑定了车位
    const vehiclesWithBindings = selectedRows.value.filter(row => 
      row.vehicleSpaces && row.vehicleSpaces.length > 0
    );
    
    let confirmMessage = `确定要删除选中的${selectedRows.value.length}辆车辆吗？`;
    if (vehiclesWithBindings.length > 0) {
      const plateNos = vehiclesWithBindings.map(v => v.plateNo).join('、');
      confirmMessage = `选中的车辆中有${vehiclesWithBindings.length}辆已绑定车位（${plateNos}），删除后将同时解除所有车位绑定。确定要继续删除吗？`;
    }
    
    await ElMessageBox.confirm(
      confirmMessage,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const ids = selectedRows.value.map((row) => row.id);
    const response = await batchDeleteVehicle(ids);
    if (response.code === 0) {
      ElMessage.success("批量删除成功");
      fetchVehicleList();
    } else {
      ElMessage.error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    
    let response;
    if (formData.id) {
      // 编辑车辆
      response = await updateVehicle(formData as Vehicle);
    } else {
      // 添加车辆
      const createData: CreateVehicleRequest = {
        cellId: formData.cellId!,
        plateNo: formData.plateNo!,
        ownerName: formData.ownerName!,
        contactPhone: formData.contactPhone!,
        ownerType: formData.ownerType!,
        remark: formData.remark,
      };
      response = await createVehicle(createData);
    }

    if (response.code === 0) {
      ElMessage.success(formData.id ? "更新成功" : "创建成功");
      dialogVisible.value = false;
      fetchVehicleList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败");
  }
};

// 显示导入对话框
const showImportDialog = () => {
  importDialogVisible.value = true;
  selectedFile.value = null;
  // 重置上传组件状态
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
};

// 文件选择处理
const handleFileChange = (file: any) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isExcel) {
    ElMessage.error('只能上传.xlsx/.xls文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过10MB!');
    return false;
  }

  selectedFile.value = file.raw;
  return true;
};

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await exportVehicleTemplate();
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '车辆导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('模板下载成功');
  } catch (error) {
    console.error('下载模板失败:', error);
    ElMessage.error('下载模板失败');
  }
};

// 处理导入
const handleImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning("请先选择要导入的文件");
    return;
  }

  importLoading.value = true;
  try {
    const response = await importVehicles(selectedFile.value);
    if (response.code === 0) {
      ElMessage.success("导入成功");
      importDialogVisible.value = false;
      selectedFile.value = null;
      // 重置上传组件状态
      if (uploadRef.value) {
        uploadRef.value.clearFiles();
      }
      // 刷新列表
      await fetchVehicleList();
    } else {
      ElMessage.error(response.message || "导入失败");
    }
  } catch (error) {
    console.error("导入失败:", error);
    ElMessage.error("导入失败");
  } finally {
    importLoading.value = false;
  }
};

// 绑定车位
const handleBindParkingSpace = async (row: Vehicle) => {
  try {
    // 获取车辆详情以获取cellId
    const response = await getVehicleById(row.id);
    if (response.code === 0 && response.data) {
      currentVehicle.value = response.data;
      
      // 重置表单
      bindParkingSpaceForm.vehicleId = row.id;
      bindParkingSpaceForm.parkingSpaceId = undefined;
      bindParkingSpaceForm.bindType = 1;
      bindParkingSpaceForm.authorizeStart = undefined;
      bindParkingSpaceForm.authorizeEnd = undefined;
      
      // 清空车位列表
      parkingSpaceList.value = [];
      
      // 打开对话框
      bindParkingSpaceDialogVisible.value = true;
    } else {
      ElMessage.error("获取车辆信息失败");
    }
  } catch (error) {
    console.error("获取车辆信息失败:", error);
    ElMessage.error("获取车辆信息失败");
  }
};

// 搜索车位
const searchParkingSpaces = async (query: string) => {
  if (!query || !currentVehicle.value) {
    parkingSpaceList.value = [];
    return;
  }
  
  try {
    parkingSpaceSearchLoading.value = true;
    const response = await searchParkingSpacesApi(query, currentVehicle.value.cellId);
    if (response.code === 0 && response.data) {
      parkingSpaceList.value = response.data;
    } else {
      parkingSpaceList.value = [];
    }
  } catch (error) {
    console.error("搜索车位失败:", error);
    parkingSpaceList.value = [];
  } finally {
    parkingSpaceSearchLoading.value = false;
  }
};

// 车位选择改变
const handleParkingSpaceChange = (parkingSpaceId: number) => {
  bindParkingSpaceForm.parkingSpaceId = parkingSpaceId;
};

// 时间限制函数
const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
};

const disabledStartTime = (date: Date) => {
  const now = new Date();
  if (date.toDateString() === now.toDateString()) {
    const hour = now.getHours();
    const minute = now.getMinutes();
    return {
      disabledHours: () => {
        const hours = [];
        for (let i = 0; i < hour; i++) {
          hours.push(i);
        }
        return hours;
      },
      disabledMinutes: (selectedHour: number) => {
        if (selectedHour === hour) {
          const minutes = [];
          for (let i = 0; i < minute; i++) {
            minutes.push(i);
          }
          return minutes;
        }
        return [];
      },
    };
  }
  return {};
};

const disabledEndDate = (time: Date) => {
  if (!bindParkingSpaceForm.authorizeStart) return false;
  
  const startDate = new Date(bindParkingSpaceForm.authorizeStart);
  const endDate = new Date(time);
  
  // 如果是临时绑定，限制在开始时间到开始时间+7天之间
  if (bindParkingSpaceForm.bindType === 2) {
    const maxDate = new Date(startDate);
    maxDate.setDate(maxDate.getDate() + 7);
    return endDate < startDate || endDate > maxDate;
  }
  
  return endDate < startDate;
};

const disabledEndTime = (date: Date) => {
  if (!bindParkingSpaceForm.authorizeStart) return {};
  
  const startDate = new Date(bindParkingSpaceForm.authorizeStart);
  const endDate = new Date(date);
  
  if (endDate.toDateString() === startDate.toDateString()) {
    const startHour = startDate.getHours();
    const startMinute = startDate.getMinutes();
    
    return {
      disabledHours: () => {
        const hours = [];
        for (let i = 0; i < startHour; i++) {
          hours.push(i);
        }
        return hours;
      },
      disabledMinutes: (selectedHour: number) => {
        if (selectedHour === startHour) {
          const minutes = [];
          for (let i = 0; i < startMinute; i++) {
            minutes.push(i);
          }
          return minutes;
        }
        return [];
      },
    };
  }
  return {};
};

// 提交绑定车位
const handleBindParkingSpaceSubmit = async () => {
  if (!bindParkingSpaceFormRef.value) return;

  try {
    await bindParkingSpaceFormRef.value.validate();
    
    const response = await bindVehicleToParkingSpace(bindParkingSpaceForm as BindVehicleRequest);
    
    if (response.code === 0) {
      ElMessage.success("绑定车位成功");
      bindParkingSpaceDialogVisible.value = false;
      fetchVehicleList();
    } else {
      ElMessage.error(response.message || "绑定车位失败");
    }
  } catch (error) {
    console.error("绑定车位失败:", error);
    ElMessage.error("绑定车位失败");
  }
};

// 组件挂载
onMounted(() => {
  fetchVehicleList();
  fetchCommunityList();
});
</script>

<style scoped>
.main {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 车位标签容器 - 固定高度，内容居中 */
.space-tags-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;
  min-height: 32px;
  padding: 4px 0;
  gap: 4px;
}

/* 车位标签样式 */
.space-tag {
  margin: 0;
  font-size: 12px;
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  border-radius: 4px;
  background-color: #f0f9ff;
  color: #0369a1;
  border: 1px solid #bae6fd;
}

/* 时间容器 - 固定高度，内容居中 */
.time-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  min-height: 32px;
  padding: 4px 0;
}

/* 时间项样式 */
.time-item {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  margin: 0;
  padding: 1px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}

/* 确保表格行高度一致 */
:deep(.el-table .el-table__row) {
  height: 48px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
  vertical-align: middle;
}

/* 当内容为空时的样式 */
.space-tags-container:empty::before,
.time-container:empty::before {
  content: "-";
  color: #c0c4cc;
  font-size: 14px;
}

:deep(.el-button--text) {
  padding: 0;
  margin-right: 8px;
}

:deep(.el-tag) {
  font-size: 12px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 导入对话框样式 */
.import-dialog-content {
  padding: 20px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.import-tips {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.import-tips h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.import-tips p {
  margin: 5px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 车位标签样式 */
.space-tag-long {
  background-color: #e1f3d8;
  color: #67c23a;
  border-color: #b3e19d;
  cursor: pointer;
}

.space-tag-temp {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #f5dab1;
  cursor: pointer;
}

.space-tag-long:hover,
.space-tag-temp:hover {
  opacity: 0.8;
}

/* 车辆车位详情样式 */
.vehicle-space-detail {
  padding: 20px 0;
}

.vehicle-space-detail .detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.vehicle-space-detail .label {
  width: 120px;
  font-weight: 600;
  color: #303133;
}

.vehicle-space-detail .value {
  flex: 1;
  color: #606266;
}
</style>
